package com.sjr.easy.chat.business;

import com.sjr.easy.chat.model.ChatGroupUser;
import com.sjr.easy.chat.model.Contact;
import com.sjr.easy.chat.model.Conversation;
import com.sjr.easy.chat.service.ChatGroupUserService;
import com.sjr.easy.chat.service.ContactService;
import com.sjr.easy.chat.service.ConversationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
public class ConversationBusiness {

    @Autowired
    private ContactService contactService;

    @Autowired
    private ConversationService conversationService;

    @Autowired
    private ChatGroupUserService chatGroupUserService;

    public Conversation getOrCreateConversation(Integer type, Long selfUserId, Long friendUserId, Long chatGroupId) {
        log.info("selfUserId:{}, friendUserId:{}", selfUserId, friendUserId);
        if (type == 1) {
            Contact contact = contactService.getContact(selfUserId, friendUserId);
            Objects.requireNonNull(contact, "没有好友关系，无法建立聊天会话");
        } else {
            ChatGroupUser chatGroupUser = chatGroupUserService.selectByUserIdAndChatGroupId(selfUserId, chatGroupId);
            Objects.requireNonNull(chatGroupUser, "用户不在此群内，无法发送消息");
        }
        Conversation conversation = conversationService.getConversation(selfUserId, friendUserId, chatGroupId);
        if (conversation != null) {
            return conversation;
        }
        try {
            conversationService.createConversation(type, selfUserId, friendUserId, chatGroupId);
        } catch (DuplicateKeyException exception) {
            log.info("会话已经存在:");
        }
        return conversationService.getConversation(selfUserId, friendUserId, chatGroupId);
    }


}
